<template>
  <div class="app-page">
    <div class="table">
      <el-table-form ref="form">

        <el-form-item class="merge-item">
          <el-select v-model="qType" style="width: 180px; margin-right: 2px;">
            <el-option label="编号" value="planCode" />
            <el-option label="计划名称" value="planName" />
            <el-option label="创建人" value="createUser" />
            <el-option label="审核人" value="auditor" />
          </el-select>
          <el-input v-model="param" placeholder="请输入" clearable />
        </el-form-item>

        <el-form-item :table-form-merge="2" class="merge-item">
          <el-select v-model="rType" style="width: 230px; margin-right: 2px;">
            <el-option label="合格率" value="passRate" />
            <el-option label="完成率" value="checkedRate" />
          </el-select>
          <el-input v-model="startRate" placeholder="请输入" clearable @input="onInput($event)" @blur="formatInput($event)" />至
          <el-input v-model="endRate" placeholder="请输入" clearable @input="onInput1($event)" @blur="formatInput1($event)" />
        </el-form-item>

        <el-form-item class="merge-item" label="状态">
          <el-select v-model="query.planStatus" style="width: 180px; margin-right: 2px;">
            <el-option label="待审核" :value="1" />
            <el-option label="执行中" :value="2" />
            <el-option label="已完成" :value="3" />
            <el-option label="作废" :value="-1" />
          </el-select>
        </el-form-item>

        <el-form-item :table-form-merge="2" class="merge-item">
          <el-select v-model="timeType" style="width: 170px; margin-right: 2px;">
            <el-option label="创建日期" value="createTime" />
            <el-option label="审核日期" value="auditDt" />
          </el-select>
          <el-date-picker
            v-model="date"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </el-form-item>

        <el-form-item label="安检范围:">
          <el-tree-select
            v-model="orgIds"
            :clearable="false"
            class="tree-select"
            :popover-width="360"
            :select-params="{
              clearable: true,
              multiple: true,
              placeholder: '请选择',
            }"
            :tree-params=" {
              'default-expand-all': true,
              'expand-on-click-node': false,
              'highlight-current': true,
              props:{
                value:'orgId',
                label: 'orgName',
                disabled: 'disabled',
              },
              data: treeData
            }"
          />
        </el-form-item>

        <template v-slot:btns>
          <el-button type="primary" icon="el-icon-search" @click="search">查询</el-button>
        </template>
      </el-table-form>
      <div style="margin-bottom: 10px;" class="btn-group">
        <div>
          <el-button type="primary" icon="el-icon-plus" @click="add">新增</el-button>
          <el-button type="primary" icon="el-icon-download" @click="exportFile">导出</el-button>
        </div>
      </div>
      <lb-table
        ref="lbTable"
        v-loading="$loadingPlugin.fetchData"
        v-el-height-adaptive-table="{bottomOffset:10}"
        border
        highlight-current-row
        element-loading-text="加载中"
        :column="column"
        :data="tableData.data"
        pagination
        :total="tableData.total"
        custom-column
        default-open
        @fetch="fetchData"
      />
    </div>
    <plan-info ref="planInfo" :csm-type-map="csmTypeMap" :tree-data="treeData" />
    <add ref="add" :tree-data="treeData" :csm-type-map="csmTypeMap" :csm-status-map="csmStatusMap" />
    <newly-increased ref="newlyIncreased" :csm-type-map="csmTypeMap" :tree-data="treeData" :csm-status-map="csmStatusMap" @upDataTable="upDataTable" />
  </div>
</template>

<script>
  import getTreeData from '@/utils/jsonTree'
  import { mapGetters } from 'vuex'
  import { parseTime, formatColumnMap } from '@/utils'
  import { mergeAsyncFunc } from '@/utils/mergeAsyncFunc'
  import { gasCheckPlanList, gasCheckPlanExport, queryExportDomain, gasCheckPlanInvalid, gasCheckPlanAudit, queryMap } from '@/api'
  import moment from 'dayjs'
  import PlanInfo from './components/PlanInfo.vue'
  import Add from './components/Add.vue'
  import NewlyIncreased from './components/NewlyIncreased.vue'

  export default {
    name: 'security-plan',
    components: {
      PlanInfo,
      Add,
      NewlyIncreased
    },
    data() {
      return {
        treeData: [],
        qType: 'planCode',
        param: '',
        rType: 'passRate',
        startRate: '',
        endRate: '',
        timeType: 'createTime',
        orgIds: [],
        actionColWidth: 80,
        exportDomain: {},
        csmTypeMap: [], // 客户类型
        csmStatusMap: [], // 客户状态
        query: {
          planStatus: ''
        },
        params1: {},
        date: [moment().startOf('month'), moment().endOf('hour')],
        tableData: {
          total: 0,
          data: []
        }
      }
    },
    computed: {
      ...mapGetters([
        'orgList'
      ]),
      column: function() {
        return [
          {
            prop: 'planCode',
            label: '编号',
            width: 150,
            render: (h, { row, $index }) => {
              return (
                <div>
                  <el-link size='mini' onClick={() => this.oneDetail(row)}>{row.planCode}</el-link>
                </div>
              )
            }
          },
          {
            prop: 'planName',
            label: '计划名称',
            width: 150
          },
          {
            prop: 'totalCount',
            label: '安检户数',
            width: 150
          },
          {
            prop: 'checkedRate',
            label: '完成率',
            width: 150,
            render: (h, { row }) => {
              return <span>{row.checkedRate === 0 ? 0 + '%' : row.checkedRate / 100 + '%'}</span>
            }
          },
          {
            prop: 'passRate',
            label: '合格率',
            width: 150,
            render: (h, { row }) => {
              return <span>{row.passRate === 0 ? 0 + '%' : row.passRate / 100 + '%'}</span>
            }
          },
          {
            prop: 'scopeNames',
            label: '安检范围',
            width: 150
          },
          {
            prop: 'planStatus',
            label: '状态',
            width: 150,
            render: (h, { row }) => {
              var obj = {
                1: '待审核',
                2: '执行中',
                3: '已完成'
              }
              return <span>{obj[row.planStatus] === undefined ? '作废' : obj[row.planStatus] }</span>
            }
          },
          {
            prop: 'createUser',
            label: '创建人',
            width: 150
          },
          {
            prop: 'createTime',
            label: '创建日期',
            width: 150,
            render: (h, { row }) => <span>{ row.createTime && parseTime(row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
          },
          {
            prop: 'auditor',
            label: '审核人',
            width: 100
          },
          {
            prop: 'auditDt',
            label: '审核日期',
            width: 150,
            render: (h, { row }) => <span>{ row.auditDt && parseTime(row.auditDt, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
          },
          {
            prop: 'remark',
            label: '备注',
            width: 150
          },
          {
            label: '操作',
            className: 'action-col',
            width: this.actionColWidth,
            align: 'center',
            fixed: 'right',
            render: (h, { row, $index }) => {
              return (
                <div>
                  { row.planStatus === 1 && <el-link size='mini' onClick={() => this.oneEdit(row)}>编辑</el-link>}
                  { row.planStatus === 1 && <el-link size='mini' onClick={() => this.oneReview(row)}>审核</el-link>}
                   <el-link size='mini' onClick={() => this.oneDetail(row)}>详情</el-link>
                  { row.planStatus === 1 && <el-link size='mini' onClick={() => this.oneDelete(row)}>作废</el-link>}
                </div>
              )
            }
          }
        ]
      }
    },
    async created() {
      await Promise.all([this.getTreeData(), this.getExportDomain(), this.queryOptionsMap()])
    },
    methods: {
      async fetchData({ currentPage, pageSize }) {
        this.query.pageIndex = currentPage
        this.query.pageSize = pageSize
        const params = {
          ...this._getQuery(this.query)
        }
        if (!this.query.planStatus) {
          params.planStatus = 0
        }
        params.orgIds = this.orgIds
        this.param ? params[this.qType] = this.param : ''
        if (this.startRate && this.endRate) {
          params[this.rType] = this.startRate * 100
          params[`${this.rType}End`] = this.endRate * 100
        }
        if (this.date && this.date.length === 2) {
          if (this.timeType === 'createTime') {
            params[this.timeType] = moment(this.date[0]).format()
            params[`${this.timeType}End`] = moment(this.date[1]).format()
          } else {
            params[this.timeType] = moment(this.date[0]).format()
            params[`auditEndDt`] = moment(this.date[1]).format()
          }
        }
        this.params1 = {}
        this.params1 = params
        const res = await gasCheckPlanList(params)
        this.tableData.data = res.data.rows
        if (currentPage === 1) this.tableData.total = res.data.total
        this.flexColumnWidth()
      },
      // 更新
      async upDataTable() {
        await this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 查询
      async search() {
        await this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 新增
      async add(row) {
        await this.$refs.add.open()
      },
      // 导出
      async exportFile() {
        const _this = this
        this.$confirm(`确定导出数据？`, '提示', {
          type: 'info'
        }).then(() => {
          const copyColumn = JSON.parse(JSON.stringify(this.column))
          copyColumn.pop()
          const str = {}
          copyColumn.forEach(item => {
            str[item.prop] = item.label
          })
          gasCheckPlanExport({
            paramInfo: _this._getQuery(_this.params1),
            kv: str // 表格列
          }).then((res) => {
            console.log('res', res)
            window.open(`${this.exportDomain}/page/export/frame?key=${res.data}`, '_blank')
          })
        })
      },
      // 获取导出域名
      getExportDomain() {
        mergeAsyncFunc(queryExportDomain)
          .then((res) => {
            this.exportDomain = res.data
          })
      },
      // 编辑
      async oneEdit(row) {
        const csmTypes = formatColumnMap(this.csmTypeMap, 'value', row.csmTypes, 'desc')
        const obj = {
          ...row,
          csmTypes: csmTypes
        }
        this.$refs.newlyIncreased.open(obj)
      },
      // 审核
      async oneReview(row) {
        this.$confirm(`确定审核此条数据?`, '提示', {
          type: 'info'
        }).then(async() => {
          const { status } = await gasCheckPlanAudit({
            planCode: row.planCode
          })
          if (status === 200) {
            this.$message({
              type: 'success',
              message: '审核成功'
            })
            this.$refs.lbTable.fetch({ currentPage: 1 })
          }
        })
      },
      // 详情
      oneDetail(row) {
        console.log('row', row)
        this.$refs.planInfo.open(row)
      },
      // 作废
      oneDelete(row) {
        this.$confirm(`确定作废此条数据`, '提示', {
          type: 'info'
        }).then(async() => {
          const { status } = await gasCheckPlanInvalid({
            planCode: row.planCode
          })
          if (status === 200) {
            this.$message({
              type: 'success',
              message: '作废成功'
            })
            this.$refs.lbTable.fetch({ currentPage: 1 })
          }
        })
      },
      // 清除对象空属性
      _getQuery(obj) {
        const query = {}
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] !== '') {
              query[key] = obj[key]
            }
          }
        }
        return query
      },
      // 获取组织机构数据
      async getTreeData() {
        const data = this.orgList.map(item => ({
          label: item.name,
          ...item
        }))
        this.treeData = getTreeData(data)
      },
      // 查询枚举
      async queryOptionsMap() {
        const [res1, res2] = await Promise.all([mergeAsyncFunc(queryMap, { enumName: 'CustomerType' }), mergeAsyncFunc(queryMap, { enumName: 'CustomerStatus' })])
        this.csmTypeMap = res1.data // 客户类型
        this.csmStatusMap = res2.data // 客户状态
      },
      // 自适应表格列宽
      flexColumnWidth() {
        this.$nextTick(() => {
          let max = 0
          const actionColDom = document.getElementsByClassName('action-col')
          for (let i = 0; i < actionColDom.length; i++) {
            if (actionColDom[i].tagName === 'TD') {
              let width = 20
              const linkDom = actionColDom[i].childNodes[0].childNodes[0].childNodes
              linkDom.forEach(it => {
                width += (it.offsetWidth + 10)
              })
              if (width > max) max = width
            }
          }
          this.actionColWidth = max > 60 ? max - 10 : 50
        })
      },
      // 格式化金额
      onInput(value) {
        const res = value
          .replace(/[^\d.]/g, '')
          .replace(/\.{2,}/g, '.')
          .replace(/^\./g, '')
          .replace('.', '$#$')
          .replace(/\./g, '')
          .replace('$#$', '.')
          .replace(/^0\d+|^\./g, '')
          .replace(/^(.*\..{2}).*$/, '$1')
        this.startRate = res
      },
      onInput1(value) {
        const res = value
          .replace(/[^\d.]/g, '')
          .replace(/\.{2,}/g, '.')
          .replace(/^\./g, '')
          .replace('.', '$#$')
          .replace(/\./g, '')
          .replace('$#$', '.')
          .replace(/^0\d+|^\./g, '')
          .replace(/^(.*\..{2}).*$/, '$1')
        this.endRate = res
      },
      async formatInput(e) {
        if (e.target.value) {
          this.startRate = (e.target.value * 1).toFixed(2)
        }
      },
      async formatInput1(e) {
        if (e.target.value) {
          this.endRate = (e.target.value * 1).toFixed(2)
        }
      }
    }
  }
</script>

<style lang="scss" scoped>
</style>
